package com.usian.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.dtos.WmUserDto;
import com.usian.model.media.pojos.WmUser;
import com.usian.utils.common.AppJwtUtil;
import com.usian.wemedia.mapper.WmUserMapper;
import com.usian.wemedia.service.WmUserLoginService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.List;

@Service
public class WmUserLoginServiceImpl extends ServiceImpl<WmUserMapper, WmUser>
        implements WmUserLoginService {

    @Override
    public ResponseResult login(WmUserDto dto) {
        if (StringUtils.isBlank(dto.getName())||StringUtils.isBlank(dto.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"账号或密码不正确");
        }

        //根据用户名查询数据库用户
        QueryWrapper<WmUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(WmUser::getName,dto.getName());
        List<WmUser> wmUserList = this.list(queryWrapper);

        //判断wmUserList是否有值
        if (wmUserList.size()>0){
            WmUser wmUser = wmUserList.get(0); // 有，则取值
            //                             用户输入的密码    +      数据库的盐值 得新密码串newPaw
            String newPaw = DigestUtils.md5DigestAsHex((dto.getPassword().concat(wmUser.getSalt()).getBytes()));
            //比较字符串
            if (wmUser.getPassword().equals(newPaw)){
                HashMap<String, Object> map = new HashMap<>();
                wmUser.setPassword("");
                wmUser.setSalt("");
                map.put("token",AppJwtUtil.getToken(wmUser.getId().longValue()));
                map.put("user",wmUser);
                return ResponseResult.okResult(map);
            }else {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
            }
        }else {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
    }
}
